const jwt = require('jsonwebtoken');
const { setJson } = require("./index");

const sign = (jtJson = {}, options = {}) => {
  const token = jwt.sign({ iss: 'lesscode', ...jtJson}, "secret", { expiresIn: 60 * 60 * 24, ...options})
  return token
}

const getVerResult = (req, res, next) => {
  const { url, headers: { token } } = req
  if(url.indexOf('/user/') > -1 || url.indexOf('/common/') > -1) {
    next()
  } else {
    if(!token) {
      setJson(res, 403, "请登录", null)
    } else {
      const { iat, exp, message = '' } = jwt.verify(token, 'secret', (error, decoded) => {
        if(error) {
          if(error.name === 'TokenExpiredError') {
            return {
              iat: 1,
              exp: 0,
              message: "token已过期"
            }
          } else if (error.name === 'JsonWebTokenError') {
            return {
              iat: 1,
              exp: 0,
              message: "token无效"
            }
          }
        } else {
          return decoded
        }
      })
      if(iat < exp) {
        next()
      } else {
        setJson(res, 403, message, null)
      }
    }
  }
}

module.exports = {
  sign,
  getVerResult
}